import 'dart:async';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_is_know_dialog.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/singleton/constant_repository/constant_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_category_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_media_play_module_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_detail_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_water_list_page.dart';
import 'package:e_reception_flutter/utils/common_select_util.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import 'event/refresh_smart_home_category_event.dart';

/// 智能家居更多操作
class SmartHomeMoreOperationsPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SmartHomeMoreOperationsPage";
  //品牌或门店信息
  final ComSmarthomeBean infoBean;

  const SmartHomeMoreOperationsPage(
      {Key key, this.infoBean,}) : super(key:key);

  @override
  _SmartHomeMoreOperationsPageState createState() => _SmartHomeMoreOperationsPageState();

  static Future<dynamic> navigatorPush(BuildContext context, ComSmarthomeBean infoBean){
    return RouterUtils.routeForFutureResult(
        context,
        SmartHomeMoreOperationsPage(
          infoBean: infoBean,
        ),
        routeName: SmartHomeMoreOperationsPage.ROUTER
    );
  }
}

class _SmartHomeMoreOperationsPageState
    extends BaseState<SmartHomeMoreOperationsPage> {

  SmartHomeViewModel _viewModel;
  SmartHomeStoreDetailViewModel _detailViewModel;
  ComSmarthomeBean _infoBean;
  StreamSubscription _categoryUpdateStreamSubscription;
  String _cacheKey;
  int _storeCount;
  int _changeInterval;
  @override
  void initState() {
    super.initState();
    _viewModel = SmartHomeViewModel(this);
    _detailViewModel = SmartHomeStoreDetailViewModel(this);
    _infoBean = widget?.infoBean;
    if(StringUtils.isNotEmpty(_infoBean?.shid)){
      _cacheKey = NetApi.GET_CATEGORY_LIST + (UserRepository.getInstance().getCacheKeySuffix()?? "")
          + _infoBean?.shid;
    }
    _categoryUpdateStreamSubscription =
        VgEventBus.global.on<RefreshSmartHomeCategoryEvent>()?.listen((event) {
          _detailViewModel?.getCategoryOnLine(_infoBean?.shid, _cacheKey, null);
        });
    _detailViewModel?.categoryValueNotifier?.addListener(() {
      setState(() {
        _infoBean = _detailViewModel?.categoryValueNotifier?.value?.comSmarthome;
      });
    });

    SharePreferenceUtil.getInt(SP_STORE_COUNT).then((value) {
      setState(() {
        _storeCount = value;
      });

      print("_storeCount:" + value.toString());
    });
    _changeInterval = UserRepository.getInstance().userData?.companyInfo?.cpsecond??15;
  }


  @override
  void dispose() {
    _categoryUpdateStreamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          resizeToAvoidBottomPadding: false,
          backgroundColor: Color(0xFFF6F7F9),
          body: _toMainColumnWidget(),
        )
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: [
        _toTopBarWidget(),
        _toWaterWidget(),
        SizedBox(height: 1,),
        _toMediaPlayWidget(),
        SizedBox(height: 1,),
        _toMediaPlayIntervalWidget(),
        Spacer(),
        _toDeleteWidget(),
      ],
    );
  }

  ///文件水印
  Widget _toWaterWidget(){
      return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: (){
          SmartHomeWaterListPage.navigatorPush(context, _infoBean);
        },
        child: Container(
          height: 50,
          alignment: Alignment.center,
          color: Colors.white,
          child: Row(
            children: [
              SizedBox(width: 15,),
              Text(
                "文件水印",
                style: TextStyle(
                  fontSize: 14,
                  color: Color(0XFF5E687C),
                ),
              ),
              Spacer(),
              Text(
                _infoBean.getWaterStatus(),
                style: TextStyle(
                  fontSize: 14,
                  color: (_infoBean.isWaterOpen())?Color(0XFF21263C):Color(0XFFB0B3BF),
                ),
              ),
              SizedBox(width: 9,),
              Image.asset(
                "images/icon_arrow_right_grey.png",
                width: 6,
                color: Color(0XFF8B93A5),
              ),
              SizedBox(width: 15,),
            ],
          ),
        ),
      );
  }

  ///文件播放
  Widget _toMediaPlayWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        SmartHomeMediaPlayModulePage.navigatorPush(context, _infoBean);
      },
      child: Container(
        height: 50,
        alignment: Alignment.center,
        color: Colors.white,
        child: Row(
          children: [
            SizedBox(width: 15,),
            Text(
              "文件播放",
              style: TextStyle(
                fontSize: 14,
                color: Color(0XFF5E687C),
              ),
            ),
            Spacer(),
            Text(
              _infoBean.getPlayStatus(),
              style: TextStyle(
                fontSize: 14,
                color: Color(0XFF21263C),
              ),
            ),
            SizedBox(width: 9,),
            Image.asset(
              "images/icon_arrow_right_grey.png",
              width: 6,
              color: Color(0XFF8B93A5),
            ),
            SizedBox(width: 15,),
          ],
        ),
      ),
    );
  }

  ///文件切换
  Widget _toMediaPlayIntervalWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        SelectUtil.showListSelectDialog(
            context: context,
            title: "图片切换时间",
            positionStr: "${_changeInterval??15}秒",
            textList: ConstantRepository.of().getMediaChangeInterval(),
            onSelect: (dynamic value) {
              _changeInterval = int.parse(value.toString().replaceAll("秒", ""));
              UserRepository.getInstance().userData?.companyInfo?.cpsecond = _changeInterval;
              setState(() {});
              _detailViewModel.updateMediaChangeInterval(context, _changeInterval);
            },
          bgColor: Colors.white,
          titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
          itemColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
        );
      },
      child: Container(
        height: 50,
        alignment: Alignment.center,
        color: Colors.white,
        child: Row(
          children: [
            SizedBox(width: 15,),
            Text(
              "文件切换",
              style: TextStyle(
                fontSize: 14,
                color: Color(0XFF5E687C),
              ),
            ),
            Spacer(),
            Text(
              "${_changeInterval??15}秒",
              style: TextStyle(
                fontSize: 14,
                color: Color(0XFF21263C),
              ),
            ),
            SizedBox(width: 9,),
            Image.asset(
              "images/icon_arrow_right_grey.png",
              width: 6,
              color: Color(0XFF8B93A5),
            ),
            SizedBox(width: 15,),
          ],
        ),
      ),
    );
  }

  ///页面标题
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "更多设置",
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      // rightWidget: _toSaveButtonWidget(),
    );
  }

  ///删除门店
  Widget _toDeleteWidget(){
    return Visibility(
      visible: (((_storeCount??0) > 1) || (!UserRepository.getInstance().isSmartHomeCompany())),
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: ()async{
          if((_infoBean?.terCnt??0) > 0){
            CommonISeeDialog.navigatorPushDialog(context,
                title: "提示",
                content:"该门店已关联显示屏，无法删除",
              confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
              titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
              contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
              widgetBgColor: Colors.white,
            );
            return;
          }
          bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: "确认删除当前智能家居品牌(${_infoBean?.name})？",
            cancelText: "取消",
            confirmText: "确认",
            confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
            cancelBgColor: Color(0xFFF6F7F9),
            titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
            contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
            widgetBgColor: Colors.white,
          );
          if (result ?? false) {
            _viewModel.deleteStore(context, _infoBean?.shid);
          }
        },
        child: Container(
          height: 50,
          alignment: Alignment.center,
          margin: EdgeInsets.only(bottom: 50 + ScreenUtils.getBottomBarH(context)),
          child: Text(
            "删除品牌/门店",
            style: TextStyle(
              color: Color(0XFFF95355),
              fontSize: 14
            ),
          ),
        ),
      ),
    );
  }
}
